<!--
 * @Author: your name
 * @Date: 2022-04-09 13:32:40
 * @LastEditTime: 2022-06-25 10:06:55
 * @LastEditors: 瞿旺兴 18774621495@163.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \nien-vue3-admin\src\views\system\user\index.vue
-->
<template>
  <div class="app-container">
    <!-- 部门树区域 -->
    <el-container>
      <el-aside>
        <div class="head-dept">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            :prefix-icon="Search"
            text
            class="head"
          ></el-input>
        </div>
        <div class="head-container">
          <el-tree
            ref="treeRef"
            :data="deptList"
            :props="{ label: 'label', children: 'children' }"
            :filter-node-method="filterNode"
            default-expand-all
            @node-click="handleNodeClick"
          ></el-tree>
        </div>
      </el-aside>
      <!--搜索表单 -->
      <el-main class="tableArea">
        <custom-container
          ref="customContainerRef"
          :config="mainConfig"
        ></custom-container>
        <setForm
          ref="setFormRef"
          :dept-options="deptOptions"
          @change-list="handleQuery"
        />
        <setuploadForm
          ref="setuploadFormRef"
          @change-list="handleQuery"
        ></setuploadForm>
        <dataScopeForm
          ref="setdataScopeFormRef"
          :init-dept-options="deptOptions"
        ></dataScopeForm>
      </el-main>
    </el-container>
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  watch,
  nextTick,
  computed,
  getCurrentInstance,
  defineAsyncComponent,
} from 'vue'
import { ElTree, ElButton, ElMessageBox, ElMessage, ElSwitch } from 'element-plus'

import {
  Plus,
  Edit,
  Delete,
  Search,
  Upload,
  Bottom,
  Key,
  Document,
} from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import { treeselect } from '@/api/system/dept'
import { DictDirection } from '@/store/modules/dicts'
import {
  listUserTab,
  delUser,
  resetUserPwd,
  changeUserStatus,
} from '@/api/system/user'
import {
  handleTree,
  isTest,
} from '@/utils/index'

const setForm = defineAsyncComponent(() => import('./components/setForm.vue'))
const setuploadForm = defineAsyncComponent(
  () => import('./components/setuploadForm.vue'),
)
const dataScopeForm = defineAsyncComponent(
  () => import('./components/dataScopeForm.vue'),
)
const { t } = useI18n()
interface Tree {
  id: number;
  label: string;
  children?: Tree[];
}
const deptName = ref(''),
  treeRef = ref<InstanceType<typeof ElTree>>()

// 非单个禁用
const single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  // 添加或修改配置参数对话框
  // 查询参数
  queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phoneNumber: undefined,
    status: undefined,
    deptId: undefined,
  }),

  // 搜索表单
  // queryFormRef = ref(null),
  customContainerRef = ref(null),
  setuploadFormRef = ref(null),
  deptList = ref([]),
  setFormRef = ref(undefined),
  setdataScopeFormRef = ref(undefined),
  {
    appContext: {
      config: {
        globalProperties: { $download },
      },
    },
    proxy,

  } = getCurrentInstance()
// 根据部门名称筛选树
watch(deptName, (val) => {
  treeRef.value!.filter(val)
})
//
let ids = []
// 搜索
const handleQuery = () => {
  customContainerRef.value.pageNum = 1
  customContainerRef.value.getList()
}
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
// 新增用户
const handleAdd = (row: { deptId?: number } | MouseEvent) => {
  if ('deptId' in row) {
    setFormRef.value.listForms.deptId = row.deptId
  } else {
    setFormRef.value.listForms.deptId = 100
  }
  setFormRef.value.open('新增用户')
}
const deptOptions = ref([])
const getTreeselect = () => {
  treeselect().then((res) => {
    deptList.value = handleTree(res.data, 'id')
    deptOptions.value = handleTree(res.data, 'id')
  })
}
getTreeselect()
nextTick(() => {
  resizeTree()
})
// 树形自适应高度
const resizeTree = () => {
  const el = document.querySelector('.el-tree') as any
  if (el) {
    let top = el.offsetTop
    let cur = el.offsetParent
    while (cur !== null) {
      top += cur.offsetTop
      cur = cur.offsetParent
    }
    el.height = window.innerHeight - top - 20
    nextTick(() => {
      el.style.height = `${ el.height }px`
    })
  }
}
window.addEventListener('resize', resizeTree, false)
// onBeforeUnmount(() => {
//   window.removeEventListener('resize', resizeTree)
// })
// 列表选择
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  ids = rows.map((item) => item.userId)
  single.value = rows.length != 1
  multiple.value = !rows.length
}
// 按部门查询
const handleNodeClick = (data) => {
  queryParams.value.deptId = data.id
  customContainerRef.value.getList(queryParams.value.deptId)
}
// 修改
const handleUpdate = (row: { [key: string]: any }) => {
  const userId = row?.userId || ids
  
  setFormRef.value.open('修改用户', userId)
}
// 删除
const handleDelete = (row: { [key: string]: any }) => {
  const userId = row.userId || ids
  ElMessageBox.confirm(`是否确认删除用户编号为"${ userId }"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => delUser(userId))
  .then((res) => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.info('取消删除')
    }
  })
}
// 用户导出
const handleExport = () => {
  $download(
    'system/user/export',
    { ...queryParams.value },
    `用户信息_${ new Date().getTime() }.xlsx`,
  )
}
// 用户导入
const handleImport = () => {

  setuploadFormRef.value.open('用户导入')
  // handleQuery()
}
// 重置密码
const handleResetPwd = (row: { [key: string]: any }) => {
  if (isTest()) {
    ElMessageBox.prompt(`请输入${ row.userName }的新密码`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(({ value }) => {
      resetUserPwds(row.userId, value)
    })
  } else {
    resetUserPwds(row.userId, '123456')
  }
}
const resetUserPwds = (userId, v) => {
  resetUserPwd(userId, v).then((res) => {
    res.code == 200 && alert(res.msg)
  })
}
// 数据权限
const handleDateScope = (row: { [key: string]: any }) => {
  // const dataScopeList = JSON.parse(JSON.stringify(row))
  const userId = row.userId
  setdataScopeFormRef.value.openDataScope = true
  setdataScopeFormRef.value.getList(userId)
  proxy.$nextTick(() => {
    setdataScopeFormRef.value.getUserDeptTreeselect(userId).then(res => {
      console.log(res, res.data.checkedKeys, 'select')
      
      setdataScopeFormRef.value.deptRef.setCheckedKeys(res.data.checkedKeys) 
    })
  })
}
/** 用户状态修改  */
// const emit = defineEmits(['update:modelValue'])
// 修改状态
// const handleStatusChange = (row: { [key: string]: any }) => {
//   const text = row.status == '0' ? '启用' : '停用'
//   ElMessageBox.confirm(`确认要"${ text }""${ row.userName }"用户吗?`, '警告', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning',
//   })
//   .then(() => changeUserStatus(row.userId, row.status))
//   .then((res) => {
//     if (res.code == 200) {
//       row.status = row.status === '0' ? '1' : '0'
//       ElMessage.success(`${ text }成功`)
//     } else {
//       row.status = row.status === '0' ? '1' : '0'
//       ElMessage.success(`${ text }失败`)
//     }
//   })
//   .catch((error) => {
//     if (error === 'cancel') {
//       ElMessage.info('取消操作')
//     }
//   })
// }
const mainConfig = computed(() => {
  const queryField = 'system.employeeManage.user.queryField.userManagement.'
  const btns = 'system.employeeManage.user.btns.'
  const columns = 'system.employeeManage.user.columns.userManagement.'
  const publicKey = 'public.'
  return {
    query: {
      fields: [
        {
          label: t(`${ queryField }userName`),
          prop: 'userName',
       
          option: {
            placeholder: '请输入用户账号',
          },
        },
        {
          label: t(`${ queryField }nickName`),
          prop: 'nickName',
    
          option: {
            placeholder: '请输入用户姓名',
          },
        },
        {
          label: t(`${ queryField }phoneNumber`),
          prop: 'phoneNumber',
          option: {
            placeholder: '请输入手机号码',
          },
        },
        {
          label: t(`${ queryField }status`),
          prop: 'status',
          type: 'select',
          option: {
            placeholder: '请输入用户状态',
            dictInfo: {
              dict: DictDirection.是否禁用字典,
            },
          },
        },
        {
          type: 'datePicker',
          label: t(`${ queryField }dateRange`),
          prop: 'dateRange',
          option: {
            type: 'daterange',
            placeholder: '开始时间-结束时间',
          },
        },
      ],
      queryParams: queryParams.value,
    },
    btns: [
      {
        title: t(`${ btns }add`),
        directive: [['hasPermi', ['system:user:add']]],
        onClick: handleAdd,
        icon: Plus,
      },
      {
        title: t(`${ btns }edit`),
        directive: [['hasPermi', ['system:user:edit']]],
        type: 'success',
        disabled: multiple.value,
        icon: Edit,
        onClick: handleUpdate,
      },
      {
        title: t(`${ btns }del`),
        directive: [['hasPermi', ['system:user:remove']]],
        onClick: handleDelete,
        type: 'danger',
        disabled: multiple.value,
        icon: Delete,
      },
      {
        title: t(`${ btns }import`),
        onclick: handleImport,
        type: 'info',
        icon: Upload,
        directive: [['hasPermi', ['system:user:import']]],
      },
      {
        title: t(`${ btns }export`),
        onclick: handleExport,
        type: 'warning',
        icon: Bottom,
        directive: [['hasPermi', ['system:user:export']]],
      },
    ],
    table: {
      columns: [
        {
          type: 'selection',
          minWidth: '55',
          align: 'center',
        },
        {
          label: t(`${ columns }userId`),
          prop: 'userId',
          align: 'center',
        },
        {
          label: t(`${ columns }userName`),
          prop: 'userName',
          align: 'center',
        },
        {
          label: t(`${ columns }nickName`),
          prop: 'nickName',
          align: 'center',
        },
        {
          label: t(`${ columns }employeeId`),
          prop: 'employeeId',
          align: 'center',
        },
        {
          label: t(`${ columns }deptName`),
          prop: 'deptName',
          align: 'center',
        },
        {
          label: t(`${ columns }phoneNumber`),
          prop: 'phoneNumber',
          align: 'center',
        },
        {
          label: t(`${ columns }status`),
          prop: 'status',
          align: 'center',
          directive: [['hasPermi', ['system:user:editStatus'], 'switch']],
          autoFormatter: {
            dict: DictDirection.是否禁用字典,
            rowKey: 'status',
          },
          // render(h, params) {
          //   return h(ElSwitch, {
          //     onChange: () => {
          //       handleStatusChange(params.row)
          //       console.log('handleStatusChange', params)
          //     },
          //     modelValue: params.row.status,
          //     'onUpdate:modelValue': (value) => {
          //       emit('update:modelValue', value)
          //     },
          //     activeValue: '0',
          //     inactiveValue: '1',
          //     activeColor: '#C0CCDA',
          //     inactiveColor: '#409EFF',
          //   })
          // },
        },
        {
          label: t(`${ columns }permissionKey`),
          prop: 'permissionKey',
          align: 'center',
        },
        {
          label: t(`${ columns }createTime`),
          prop: 'createTime',
          align: 'center',
        },
        {
          label: t(`${ columns }operation`),
          align: 'center',
          showOverflowTooltip: false,
          fixed: 'right',
          width: '250',
          render: (h, params) => {
            const buttons = [
              {
                title: t(`${ publicKey }edit`),
                icon: Edit,
                clickFun: handleUpdate,
              },
              {
                title: t(`${ publicKey }del`),
                icon: Delete,
                clickFun: handleDelete,
                // directive: [['hasPermi', ['system:user:remove']]],
              },
              {
                title: t(`${ publicKey }dataAccess`),
                icon: Document,
                clickFun: handleDateScope,
                directive: [['hasPermi', ['system:role:data']]],
              },
              {
                title: t(`${ publicKey }reset`),
                icon: Key,
                clickFun: handleResetPwd,
              },
            ]
            
            return buttons.map((el) => { 
              if (params.index == 0 && el.title == '删除' && params.row.userId == 1) return
              return h(
                ElButton,
                {
                  text: true,
                  type: 'primary',
                  icon: el.icon,
                  onClick: () => {
                    el.clickFun(params.row)
                  },
                },
                {
                  default: () => el.title,
                },
              )
            })
          },
        },
      ],
      event: {
        onSelectionChange: (rows) => {
          handleSelectionChange(rows)
        },
      },
    },
    api: listUserTab,
    customKey: 'system/employeeManage/user',
  }
})
</script>
<style lang="less" scoped>
.head-dept {
  margin: 20px 0;
}
:deep(.head-dept>.head) {
  height: 30px;
}
.head-container {
  overflow: hidden;
  overflow-y: hidden;
  min-width: 250px;
  background-color: #fff;
}
/* stylelint-disable-next-line no-descending-specificity */
:deep(.el-tree) {
  overflow: hidden;
  overflow-y: scroll;
  min-width: 250px;
  & > .el-tree-node {
    padding-top: 20px;
  }
  &::-webkit-scrollbar {
    min-width: 5px !important;
    height: 3px !important;
    background-color: #eee;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgb(0 0 0 / 0.2);
    height: 5px !important;
  }
}
</style>
